import mongoose from '../config/DBHelpler'
import moment from 'dayjs'
import Comments from './Comments'
import UserCollect from './UserCollect'
// import PostHistory from './PostHistory'
const Schema = mongoose.Schema
const PostSchema = new Schema({
  uid: { type: String, ref: 'users' }, // 查询users表
  title: { type: String },
  content: { type: String },
  catalog: { type: String },
  fav: { type: String },
  isEnd: { type: String, default: '0' },
  reads: { type: Number, default: 0 },
  answer: { type: Number, default: 0 },
  status: { type: String, default: '0' },
  isTop: { type: String, default: '0' },
  sort: { type: String, default: 100 },
  tags: {
    type: Array,
    default: [
      // {
      //   name: '',
      //   class: ''
      // }
    ]
  }
}, { timestamps: { createdAt: 'created', updatedAt: 'updated' } })
PostSchema.statics = {
  /**
   *获取文章列表数据
   * @param {Object} options 筛选条件
   * @param {String} sort 排序
   * @param {Number} pagefen 分页
   * @param {Number} limit 分页条数
   */
  getList: function (options, sort, page, limit) {
    return this.find(options)
      .sort({ [sort]: -1 })
      .skip(page * limit)
      .limit(limit)
      .populate({
        path: 'uid',
        select: 'name isVip pic created'
      })
  },
  countList: function (options) {
    return this.find(options).countDocuments()
  },
  // 本周热议
  getTopWeek: function () {
    return this.find({
      created: {
        $gte: moment().subtract(7, 'days')
      }
    }, {
      // 需要给出的数据
      answer: 1,
      title: 1
    }).sort({ answer: -1 })
      .limit(15)
  },
  // 文章详情
  findByTid: function (id) {
    return this.findOne({ _id: id }).populate({
      path: 'uid',
      select: 'name pic isVip _id'
    })
  },
  // 获取用户发贴记录
  getListByUid: function (id, page, limit) {
    return this.find({ uid: id })
      .skip(page * limit)
      .limit(limit)
      .sort({ created: -1 })
  },
  // 多少条数据
  countByUid: function (id) {
    return this.find({ uid: id }).countDocuments()
  },
  // 删除帖子，先删除该帖子相关的评论、收藏、浏览历史
  deleteManyAndRef: async function (conditions) {
    const postList = await this.find(conditions)
    console.log(postList.length)
    console.assert(postList.length > 0, '未找到要删除的 post 文档！')
    for (let i = 0; i < postList.length; i++) {
      await Comments.deleteManyAndRef({ tid: postList[i]._id })
      await UserCollect.deleteByPostId(postList[i]._id)
      // await PostHistory.deleteByPostId(postList[i]._id)
    }
    return this.deleteMany(conditions)
  }
}
// 保存的时候创建时间
PostSchema.pre('save', function (next) {
  this.created = moment().format('YYYY-MM-DD HH:mm:ss')
  next()
})
const POSTModel = mongoose.model('post', PostSchema)

export default POSTModel
